var $tbody = $("#sample-table-1 tbody"),
    $delete;
/**
 * 日期控件实例化
 */
console.log('111111')
jQuery(function ($) {
    $('.date-picker').datepicker({autoclose: true}).next().on(ace.click_event, function () {
        $(this).prev().focus();
    });
});

// 初始化table
$("#musicType_table").bootstrapTable({
    'url': '/community/musictype/findMusictypeList',
    'cache':false,
    //'method': 'post',
    'queryParams':function(params){
        // params["userRecommendType"] = $("#userRecommendType").val();
    	params["mark"] = true;
        params['limit'] = params.limit;
        params['offset'] = params.offset/params.limit + 1;
    	return params;
    },
    'toolbar': $('div[data-name="btnCtl"]'),
    'striped': true,
    'pagination': true,
    'sidePagination': 'server',
    'pageSize': globalPageSize,
    'pageList': [],
    'clickToSelect': false,
    'singleSelect': true,
    'smartDisplay': true,
    'responseHandler': function(resb) {
    	return {
    		'total': resb.data.total,
    		'rows': resb.data.rows
    	}
    },
    // 'onCheck': function() {
    //     $("button[data-target='#updateModal'], button[data-target='#deleteModal']").removeAttr("disabled");
    // },
    // 'onUncheck': function() {
    //     $("button[data-target='#updateModal'], button[data-target='#deleteModal']").attr("disabled", 'true');
    // },
    'columns': [{
        'checkbox': true
        // 'class': 'hide'
    }, {
        'field': 'isHide',
        'title': '隐藏',
        'align': 'center',
        'valign': 'middle',
        'class': 'hide'
    }, {
        'field': 'typeId',
        'align': 'center',
        'valign': 'middle',
        'class': 'hide ID'
    },{
        'field': 'sort',
        'title': '排序',
        'align': 'center',
        'valign': 'middle'
        // 'formatter': function (value,row,index) {
        //     index+=1;
        //     return index
        // }
    }, {
        'field': 'typeName',
        'title': '类名',
        'align': 'center',
        'valign': 'middle',
        'formatter': function(value,row,index){
            if(row.isHide == '1'){
                var data = value + " " + "<span style='color:red;'>(已隐藏)</span>";
                return data
            }else{
                return value
            }
        }
    }, {
        'field': 'typeIcon',
        'title': '图标',
        'align': 'center',
        'valign': 'middle',
        'formatter': function (typeIcon,row,index) {
            if(index != 0){
                return "<img style='width: 50px;height: 50px;' src='" +typeIcon+ "'>"
            }
        }
    }, {
        'field': 'typeId',
        'title': '操作',
        'align': 'center',
        'valign': 'middle',
        'width': 240,
        'formatter': function (typeId,row,index) {
            if(index != 0){
                return "<button class='btn btn-sm btn-success updateType' data-target='#updateModal' style='margin-right: 30px'>修改</button><button class='btn btn-sm btn-success deleteType' data-musictype='"+typeId+"'>删除</button>"
            }
        }
    }, {
        'field': 'typeId',
        'title': '查看音乐',
        'align': 'center',
        'valign': 'middle',
        'formatter': function (typeId,row,index) {
            if(index == 0){
                return "<button class='btn btn-sm btn-success checkHostMusic' data-typeid='" +typeId+ "'>查看</button>"
            }else{
                return "<button class='btn btn-sm btn-success checkMusic' data-typeid='" +typeId+ "'>查看</button>"
            }
        }
    }, {
        'field': 'typeId',
        'title': '推荐音乐',
        'align': 'center',
        'valign': 'middle',
        'formatter': function(typeId,row,index){
            if(index == 0){
                return "<button class='btn btn-sm btn-success recommendHostMusic' data-typeid='" +typeId+ "'>推荐</button>"
            }else{
                return "<button class='btn btn-sm btn-success recommendMusic' data-typeid='" +typeId+ "'>推荐</button>"
            }
        }
    }]
});

/**
 * 查看分类下的音乐
 */
$('.row').on('click','.checkMusic,.checkHostMusic',function () {
    var data = $(this).data('typeid');
    sessionStorage.setItem('musicType',data);
    $("#main-content").empty();
    loadPage('musicClassify/musicList.html')
});

/**
 * 推荐音乐
 */
$('.row').on('click','.recommendMusic,.recommendHostMusic',function () {
    var data = $(this).data('typeid');
    sessionStorage.setItem('musicTypes',data);
    $("#main-content").empty();
    loadPage('recommendMusicList/recommendList.html')
})

/**
 * 更新模态框展示
 */
$("#updateModal").on('show.bs.modal', function () {
    var tableData = $('#musicType_table').bootstrapTable('getSelections')[0],
         inputs = $(this).find('input[type=text]');
    inputs[0].value = tableData.typeName;
    inputs[1].value = tableData.sort;
    inputs[2].value = tableData.typeId;
    $('#specialImgs').attr('src',tableData.typeIcon);
    if(tableData.isHide == 1){
        $(this).find('#isHide').prop('checked',true);
        $(this).find('#isShow').prop('checked',false)
    }else{
        $(this).find('#isShow').prop('checked',true);
        $(this).find('#isHide').prop('checked',false);
    }
});

/**
 * 更新模态框展示
 */
$(document).on('click','.updateType',function () {
    $("#musicType_table").bootstrapTable("checkBy", {field:"typeId", values:[$(this).parent().siblings('.ID').html()]});
    $('#updateModal').modal('show');
    $('#updatePageAddImg').css({'height':'124px'})
});


/**
 * 更新模态框隐藏
 */
$('#updateModal').on('hidden.bs.modal',function(){
    $("#musicType_table").bootstrapTable("uncheckAll");
});

/**
 * 删除类
 */
$(document).on('click','.deleteType',function () {
    $delete = $(this);
    console.log($(this));
    $('#deleteModal').modal('show');
});

$('#deleteModal').find('#deleteType').click(function(){
    console.log($(this));
    $.ajax({
        url:'/community/musictype/deleteMusicType',
        dataType:'json',
        type:'POST',
        data:{
            'typeId':$delete.data('musictype')
        },
        success:function (resp) {
            alert(resp.message);
            $('#musicType_table').bootstrapTable('refresh')
        },
        error:function (xhr,textStatus,thrownError) {
            alert(textStatus)
        }
    });
    // return false
});

/**
 * 添加用户表单验证
 */
$('#addForm').validationEngine('attach', {
    promptPosition: 'centerRight',
    scroll: false,
    binded: true
});

/**
 * 添加模态框显示时，清空各输入元素的value
 */
$("#addModal").on('show.bs.modal', function () {
    $('#merchantImgs').removeAttr('src');
    $(this).find("input[type=text]").val("");
    $(this).find("input[type=password]").val("");
});


// $("#userRecommendType").on('change',function () {
//     $('#stationFormId').submit();
// });

/**
 * 添加头像和头像上传
 */
$(document).ready(function () {
    $("#addPageAddImg,#updatePageAddImg").click(function () {
        $('#addPageAddImg').css({'height':'124px'});
        $('.bord').addClass("borderbox");
        $('#merchantImgs,#specialImgs').css({"width": "100%", "height": "100%"});
    });
});

$(function(){
    $('#addPageAddImg,#updatePageAddImg').change(function(){
       var formdata = new FormData(),
           $that = $(this);
        if($(this).attr('id')==="addPageAddImg"){
            $.each($('#addPageAddImg')[0].files, function(i,file){
                formdata.append('file',file);
            })
        }else{
            $.each($('#updatePageAddImg')[0].files, function(i,file){
                formdata.append('file',file);
            })
        }
        $.ajax({
           url:'../common/uploadFile',
           type:'POST',
           data: formdata,
           dataType:'json',
           cache: false,
           processData : false,
           contentType : false,
           success:function (resp) {
               var url = resp.data.url;
               if(resp.code == '1'){
                   if($that.attr('id')==="addPageAddImg"){
                       // alert(resp.message);
                       $('#merchantImgs').attr('src',url)
                   }else{
                       // alert(resp.message);
                       $('#specialImgs').attr('src',url)
                   }
               }else{
                   alert("预览失败，请重新上传");
               }
           }
        });
    });
});


/**
 * 角色操作(新增，更新，删除)
 * @param action [add/update/remove]
 * @param data
 *               [add/update 数据结构 {name: string, description: string, listAuthorityId: array} ]
 *               [delete 数据结构 {roleId: int}]
 * @param async/scync [default async]
 */
function userManagement(action, data, async) {
    var url = null;
    (async === false) ? async = false: async = true;
    if (action === 'add') {
        url = '/community/musictype/addMusicType';
   } else if (action === 'update') {
       url = '/community/musictype/updateMusicType';
//    } else {
//        url = '../user/delete';
    };
    return $.ajax({
        type: "POST",
        url: url,
        data: data,
        dataType: 'json',
        async: async,
        success: function(resb) {
            alert(resb.message);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
}


/**
 * 新增模态框显示
 */
$("#addModal").on('show.bs.modal', function() {
	$(this).find('input[type=text],input[type=file]').val("");
})

/**
 * 新增,更新,删除角色表单提交
 */
$("#addForm,#updateForm,#deleteForm").submit(function() {
    if($('#addForm').validationEngine('validate') == false){
        return false;
    }
    var type = $(this).data("type"),
        $modal = $("#" + type + "Modal"),
        $inputs = $(this).find('input[type="text"]'),
        $sels = $(this).find('select'),
        tableData = $("#user_table").bootstrapTable("getSelections")[0],
        data = null;
    	if (type ==='add'){
            data = {
                'typeName':$inputs[0].value,
                'sort':$inputs[1].value,
                'typeIcon':$(this).find('#merchantImgs').attr('src'),
                'isHide':$(this).find('input[type=radio]:checked').val()
            };
        }else if(type === 'update'){
            data = {
                'typeName':$inputs[0].value,
                'sort':$inputs[1].value,
                'typeId':$inputs[2].value,
                'typeIcon':$(this).find('#specialImgs').attr('src'),
                'isHide':$(this).find('input[type=radio]:checked').val()
            }
        }
    $modal.modal('hide');
    // 完成ajax后刷新表格数据
    userManagement(type, data).done(function() {
        $("#musicType_table").bootstrapTable("refresh")
    });

    // 阻止表格冒泡事件
    return false;
});
